import { MobilePageDesigner } from 'components/mobilePageDesigner';
import { StationService, guid } from 'admin/services/station';
import { componentsDir } from 'components/common';
import { StationService as UserStation } from 'user/services/stationService';
import { Page } from 'maishu-chitu';
// import { app } from 'admin/application';
import { pageData as dataSource } from 'admin/services/dataSource';
import ReactDOM = require('react-dom');
import React = require('react');
import * as chitu from "maishu-chitu";
import { PageProps } from 'maishu-chitu-react';

let controlTypes: { [propName: string]: React.ComponentClass<any> } = {};

class State {
    pageData: PageData
}

export default class MobileDesignPage extends React.Component<PageProps, State>{
    constructor(props) {
        super(props);
        this.state = { pageData: null };
    }
    async loadControlInstance(controlId: string, controlName: string, controlHTMLElement: HTMLElement, controlData?: any) {

        controlHTMLElement.setAttribute('data-control-name', controlName);
        controlHTMLElement.setAttribute('data-control-id', controlId);
        controlHTMLElement.className = `${controlName}-control`;
        let controlType = await this.getControlType(controlName);
        let controlReactElement = React.createElement(controlType, controlData);
        let control: React.Component<any, any> = ReactDOM.render(controlReactElement, controlHTMLElement);
        return { control, type: controlType };
    }
    getControlType(controlName: string): Promise<React.ComponentClass<any>> {
        if (controlTypes[controlName] != null) {
            return Promise.resolve(controlTypes[controlName]);
        }

        return new Promise((reslove, reject) => {
            let path = `${componentsDir}/${controlName}/control`; //Editor.path(controlName);
            let self = this;
            requirejs([path], function (obj: any) {
                let controlType = (obj || {}).default as React.ComponentClass<any>;
                console.assert(controlType != null);
                controlTypes[controlName] = controlType;
                reslove(controlType);
            })
        })
    }
    async savePageData(item: PageData) {
        if (item.id)
            await dataSource.update(item);
        else
            await dataSource.insert(item);

        return item;
    }
    async componentDidMount() {
        let pageData = await getPageData(this.props.source);
        this.setState({ pageData });
    }
    render() {
        let { pageData } = this.state;
        if (pageData == null) {
            return <div className="loading">数据正在加载中...</div>
        }
        return (
            <MobilePageDesigner pageData={pageData}
                showComponentToolbar={true}
                showPageEditor={true}
                save={(pageData) => this.savePageData(pageData)}
                elementPage={this.props.source}
                rightButtons={[
                    <button key="return" className="btn btn-sm btn-primary" onClick={() => this.props.app.back()}>
                        <i className="icon-reply" />
                        <span>返回</span>
                    </button>
                ]}>
            </MobilePageDesigner>
        );
    }
}


async function getPageData(page: Page) {
    let station = page.createService(StationService);
    let userStation = page.createService(UserStation);
    let { pageId, templateId } = page.data;
    let pageData: PageData;
    if (pageId) {
        pageData = await userStation.pages.pageDataById(pageId as string);
    }
    else if (templateId) {
        pageData = await station.pageDataByTemplate(templateId as string);
        delete pageData.id;
    }
    else {
        pageData = {
            id: guid(),
            controls: []
        };
    }

    return pageData;
}